package com.leading.spring.consumer.controller;

import com.leading.spring.modal.Depatment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author chennan
 * @create 2021-05
 */

@Api("前端交互消费者请求")
@RestController
@RequestMapping("/consumer")
public class DepatmentConsumerController {

    //进行 RestTemplate 调用

    //Ribbon com.netflix.loadbalancer.IRule 轮询规则
    private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
    private static final int RESPONSE_SECCESS = 200;

    //    private static final String REST_URL_PREFIX = "http://localhost:8001";
    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation("根据id进行获取")
    @GetMapping("/get/{id}")
    public Depatment get(@PathVariable Long id) {
        ResponseEntity<Depatment> forEntity = restTemplate.getForEntity(REST_URL_PREFIX + "/depatment/query/" + id, Depatment.class);
        int value = forEntity.getStatusCode().value();
        if (value == RESPONSE_SECCESS) {
            Depatment depatment = forEntity.getBody();
            return depatment;
        }
        throw new RuntimeException("请求获取服务报错，报错信息为：" + forEntity.getStatusCode().toString());
    }

    @ApiOperation("获取全部部门")
    @GetMapping("getAll")
    public List<Depatment> getAll() {
        ResponseEntity<List> forEntity = restTemplate.getForEntity(REST_URL_PREFIX + "/depatment/query-all", List.class);
        int value = forEntity.getStatusCode().value();
        if (value == RESPONSE_SECCESS) {
            List<Depatment> depatments = forEntity.getBody();
            return depatments;
        }
        throw new RuntimeException("请求获取服务报错，报错信息为：" + forEntity.getStatusCode().toString());
    }
}
